package com.sch.wanandroid.ui.my.collect

import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.coder.zzq.smartshow.toast.SmartToast
import com.sch.wanandroid.R
import com.sch.wanandroid.adapter.MyCollectAdapter
import com.sch.wanandroid.base.BaseActivity
import com.sch.wanandroid.constants.Constants
import com.sch.wanandroid.entity.CollectBean
import com.sch.wanandroid.ui.addshare.AddShareActivity
import com.sch.wanandroid.ui.my.collect.addCollect.AddCollectActivity
import com.sch.wanandroid.ui.web.WebActivity
import com.sch.wanandroid.util.AppManager
import kotlinx.android.synthetic.main.activity_collect.*

/**
 * Created by Sch.
 * Date: 2020/4/28
 * description: 我的收藏页面
 */
class MyCollectActivity : BaseActivity() {
    private lateinit var myCollectViewModel: MyCollectViewModel
    private var pageNum: Int = 0
    private val myCollectAdapter by lazy { MyCollectAdapter() }
    private val collectList by lazy { mutableListOf<CollectBean>() }

    /**
     * 点击收藏后将点击事件上锁,等接口有相应结果再解锁
     * 避免重复点击产生的bug  false表示没锁，true表示锁住
     */
    private var lockCollectClick = false
    private var collectPosition = 0

    override fun init(savedInstanceState: Bundle?) {
        myCollectViewModel = ViewModelProvider(this).get(MyCollectViewModel::class.java)
        initTitle("我的收藏")

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = myCollectAdapter
        recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER//取消滑动到顶部边界越界效果
        initListener()

        myCollectViewModel.collectListLiveData.observe(this, Observer {
            setData(it)
        })
        myCollectViewModel.errorMsg.observe(this) {
            onError(it)
        }
        myCollectViewModel.uncollectSuccess.observe(this) {
            unCollectSuccess()
        }
    }

    override fun onStart() {
        super.onStart()
        loadingTip.loading()
        loadData()
    }

    private fun loadData() {
        collectList.clear()
        myCollectAdapter.setList(collectList)
        pageNum = 0
        myCollectViewModel.getCollectList(pageNum)
    }

    private fun initListener() {

        // 设置无网络时重新加载点击事件
        loadingTip.setReloadListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                loadingTip.loading()
                myCollectViewModel.getCollectList(pageNum)
            }
        })
        smartRefresh.setOnRefreshListener {
            pageNum = 0
            collectList.clear()
            myCollectAdapter.setList(collectList)
            myCollectViewModel.getCollectList(pageNum)
        }
        smartRefresh.setOnLoadMoreListener {
            pageNum++
            myCollectViewModel.getCollectList(pageNum)
        }
        myCollectAdapter.setOnItemClickListener { adapter, view, position ->
            intent(Bundle().apply {
                putString(Constants.WEB_URL, collectList[position].link)
                putString(Constants.WEB_TITLE, collectList[position].title)
            }, WebActivity::class.java, false)
        }
        myCollectAdapter.addChildClickViewIds(R.id.ivCollect)
        myCollectAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.ivCollect) {
                if (!AppManager.isLogin()) {
                    SmartToast.info("请先登录")
                    return@setOnItemChildClickListener
                }
                if (position < collectList.size && !lockCollectClick) {
                    lockCollectClick = true
                    collectPosition = position
                    myCollectViewModel.unCollect(
                        collectList[position].id,
                        collectList[position].originId
                    )
                }
            }
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_collect
    }

    fun setData(list: List<CollectBean>) {
        dismissRefresh()
        if (list.isNotEmpty()) {
            collectList.addAll(list)
            myCollectAdapter.setList(collectList)
        } else {
            if (collectList.size == 0) loadingTip.showEmpty()
            else SmartToast.info("没有更多数据了")
        }
    }

    fun onError(ex: String?) {
        lockCollectClick = false
        dismissRefresh()
        //请求失败将page -1
        if (pageNum > 1) pageNum--
        if (collectList.size == 0) {
            loadingTip.showInternetError()
        }
        SmartToast.error(ex)
    }

    /**
     * 隐藏刷新加载
     */
    private fun dismissRefresh() {
        loadingTip.dismiss()
        if (smartRefresh.state.isOpening) {
            smartRefresh.finishLoadMore()
            smartRefresh.finishRefresh()
        }
    }

    private fun unCollectSuccess() {
        lockCollectClick = false
        collectList.removeAt(collectPosition)
        myCollectAdapter.removeAt(collectPosition)
        if (collectList.size == 0) loadingTip.showEmpty()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_collect, menu)
        return super.onCreateOptionsMenu(menu)
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_add -> {
                intent(AddCollectActivity::class.java, true)
            }
        }
        return super.onOptionsItemSelected(item)
    }
}